import { DataTypes } from 'sequelize'
import {
  Table,
  Column,
  Model,
  Comment,
  Unique,
  AllowNull,
  Default,
  HasMany,
  AutoIncrement,
  PrimaryKey
} from 'sequelize-typescript'
import { InferAttributes, InferCreationAttributes } from 'sequelize/types'
import { defaultAvatar } from '../../config/constant'
import md5 from '../../utils/crypto'
import Blog from './Blog'

@Table({
  //表名不自动添加s
  freezeTableName: true,
  //不自动创建时间戳
  timestamps: false
})

//数据校验在joi已经执行了，所以sequelize自带的validate就不使用了，已经在发送请求的时候就验证了参数是正确的
class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
  @PrimaryKey
  @AutoIncrement
  @Column
  user_id?: number

  @Comment('用户名')
  @Unique('userName')
  @AllowNull(false)
  @Column
  userName!: string

  @Comment('密码')
  @AllowNull(false)
  @Column
  set password(value: string) {
    this.setDataValue('password', md5(value))
  }

  @Comment('昵称')
  @AllowNull(false)
  @Column
  nickName!: string

  @AllowNull(false)
  @Unique('email')
  @Comment('邮箱')
  @Column
  email!: string

  @Default(2)
  @Comment('性别:(0 女性,1 男性,2 保密)')
  @Column({ type: DataTypes.TINYINT })
  gender?: number

  @Default(defaultAvatar)
  @Comment('头像，图片地址')
  @Column
  avatar?: string
  //需要查出该用户的所有博客用hasmany
  @HasMany(() => Blog)
  blog?: Blog[]
  //但不用查出该用户的所有评论，所以不用添加对comments的关联
}
export default User
